<?php
defined('SYSPATH') OR die('No direct access allowed.');
/**
 * agama.php
 * @author ranuandra
 *
 * 30 Apr 2012 14:55:39
 *
 * 
 */

class Controller_Admin_Universitas extends Kohana_Admin
{
	public function action_index()
	{
	    $datas = ORM::factory('mstuniversitas')->find_all();
		//$datas = ORM::factory('mstuniversitas')->where('flag', '=', '0')->find_all();
	
		$view = View::factory('admin/universitas/index');
		$view->datas = $datas;
		$this->template->container = $view;
	}
	
	public function action_new()
	{
		$form = ORM::factory('mstuniversitas')->getForm();
		$view = View::factory('admin/universitas/form');
		$view->form = $form;
		$this->template->container = $view;
	}
	
	public function action_edit()
	{
		$id = Request::current()->param('id');
		$data = ORM::factory('mstuniversitas', $id)->as_array();
		$view = View::factory('admin/universitas/form');
		$view->form = $data;
		$this->template->container = $view;		
	}
	
	public function action_inactive()
	{
		$id = Request::current()->param('id');
		if($id)
		{
			$this->_setFlag($id, 0);
			Request::current()->redirect(URL::base().'admin/universitas');
			exit;
			
		}
	}
	
	public function action_active()
	{
		$id = Request::current()->param('id');
		if($id)
		{
			$this->_setFlag($id, 1);
			Request::current()->redirect(URL::base().'admin/universitas');
			exit;			
		}
	}

	
	private function _setFlag($id, $flag)
	{
			$db = Database::instance();
			$db->begin();
			
			$data = ORM::factory('mstuniversitas', $id);
			try {
				$data->flag = $flag;
				$data->save();
				$db->commit();
				
			}
			catch(ORM_Validation_Exception $e)
			{
				$db->rollback();
				$errors = $e->errors('models');
				print_r($errors);
			}		
	}
	
	
	public function action_save()
	{

		if(isset($_POST['submit']))
		{
			$db = Database::instance();
			$db->begin();
			
			try 
			{
				if(isset($_POST['id']))
				{
					$area = ORM::factory('mstuniversitas', Request::current()->post('id'));
					$area->universitas = Request::current()->post('universitas');
					$area->flag = Request::current()->post('flag');
					$area->save();
				}
				else 
				{
					$area = ORM::factory('mstuniversitas');
					$area->create_data($_POST);
				}
				
				$db->commit();
				Request::current()->redirect(URL::base().'admin/universitas');
				exit;
			}
			catch(ORM_Validation_Exception $e)
			{
				$db->rollback();
				$errors = $e->errors('models');
				print_r($errors);
			}
		}		
	}	
}